(function() {
	var $ = require(L('$')), _ = require(L('_'));

	var fb = {};
	fb.init = function() {
		Ti.Facebook.appid = L('fb_app_id');
		Ti.Facebook.permissions = ['publish_stream'];
		Ti.Facebook.forceDialogAuth = true;
		Ti.Facebook.addEventListener('login', function(e) {
			$.w('#FB_LOGIN!');
			if (e.success) {
				fb.loginHandler && fb.loginHandler(e);
			} else if (e.error) {
				$.mask(false);
				$.i('FB_LOGIN_ERROR :' + e.error);
			} else if (e.cancelled) {
				$.mask(false);
				$.i("FB_LOGIN : Canclled!");
			}
		});
	};
	fb.loginHandler = null;
	fb.login = function(callBack) {
		if (Ti.Facebook.loggedIn)
			callBack && callBack();
		//fb.init();
		// Ti.Facebook.addEventListener('login', function(e) {
			// if (e.success) {
				// callBack && callBack(e);
			// } else if (e.error) {
				// $.mask(false);
				// $.i('FB_LOGIN_ERROR :' + e.error);
			// } else if (e.cancelled) {
				// $.mask(false);
				// $.i("FB_LOGIN : Canclled!");
			// }
		// });
		fb.loginHandler = callBack;
		Ti.Facebook.authorize();
	};
	fb.logout = function() {
		if (Ti.Facebook.loggedIn)
			Ti.Facebook.logout();
	};
	fb.getFriends = function(offset, limit, callBack) {
		var requestData = {
			q : "SELECT uid, name, pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) ORDER BY name LIMIT " + limit + "OFFSET " + offset
		};
		Ti.Facebook.requestWithGraphPath('fql', requestData, 'GET', callBack);
	};
	fb.post_to_friends = function(profileIDs, shareData, callBack) {
		shareData.picture = $.isNull(shareData.picture) ? '' : shareData.picture;
		shareData.source = $.isNull(shareData.source) ? '' : shareData.source;
		var batchRequest = new Array();
		var requestBody = 'message=' + shareData.message;
		requestBody += '&picture=' + shareData.picture;
		requestBody += '&link=' + shareData.link;
		requestBody += '&name=' + $.encode_uri(shareData.name);
		requestBody += '&caption=' + shareData.caption;
		requestBody += '&description=' + $.encode_uri(shareData.description);
		requestBody += '&source=' + shareData.source;
		_.each(profileIDs, function(profileID) {
			batchRequest.push(fb.batch_request('post', profileID + '\/feed', requestBody));
		});
		var requestData = {
			batch : JSON.stringify(batchRequest)
		};
		Ti.Facebook.requestWithGraphPath('batch', requestData, 'POST', function(result) {
			$.i('SHARE_FB : ' + JSON.stringify(result));
			callBack(result);
		});
	};
	fb.post_to_my_wall = function(shareData, callBack) {
		fb.post_to_friends(['me'], shareData, callBack);
	};
	fb.batch_request = function(method, relative_url, body) {
		return {
			method : method,
			relative_url : relative_url,
			body : body
		}
	};

	module.exports = fb;
})();
